import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { workAPI } from '../services/api';
import './styles.css';

function CreateArticlePage() {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [content, setContent] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [userData, setUserData] = useState(null);
  const [userId, setUserId] = useState(null);
  
  const navigate = useNavigate();
  const location = useLocation();
  
  // 在组件加载时检查登录状态和获取传递的参数
  useEffect(() => {
    // 获取从导航传递过来的 userId
    if (location.state && location.state.userId) {
      setUserId(location.state.userId);
      console.log('从导航接收到的 userId:', location.state.userId);
    }
    checkLoginStatus();
  }, [location]);
  
  // 检查用户登录状态
  const checkLoginStatus = () => {
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    
    if (!isLoggedIn) {
      // 如果未登录，重定向到登录页面
      navigate('/login', { state: { from: '/create-article' } });
      return;
    }
    
    try {
      const storedUserData = localStorage.getItem('userData');
      if (storedUserData) {
        setUserData(JSON.parse(storedUserData));
      } else {
        navigate('/login');
      }
    } catch (error) {
      console.error('解析用户数据失败', error);
      navigate('/login');
    }
  };
  
  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 验证表单
    if (!title.trim()) {
      setError('请输入文章标题');
      return;
    }
    
    if (!content.trim()) {
      setError('请输入文章内容');
      return;
    }
    
    setIsSubmitting(true);
    setError('');
    
    try {
      // 优先使用从导航传递的 userId，如果没有则使用从 localStorage 获取的用户数据中的 userId
      const authorId = userData.userId;

      const articleData = {
        title: title.trim(),
        description: description.trim(),
        context: content.trim(),
        type: 1, // 使用默认类型
        userId: authorId
      };
      
      const response = await workAPI.saveWork(articleData);
      if (response && response.code === 200) {
        // 发布成功，重定向到文章页面
        navigate(`/article/${response.result}`);
      } else {
        setError(response?.message || '发布失败，请稍后重试');
      }
    } catch (err) {
      console.error('发布文章失败:', err);
      setError('发布文章时发生错误，请稍后重试');
    } finally {
      setIsSubmitting(false);
    }
  };
  
  // 返回到主页
  const goToHome = () => {
    navigate('/');
  };
  
  return (
    <div className="create-article-container">
      <header className="page-header">
        <h1>发布文章</h1>
        <button className="back-button" onClick={goToHome}>返回主页</button>
      </header>
      
      {error && <div className="error-message">{error}</div>}
      
      <form className="article-form" onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="title">标题 <span className="required">*</span></label>
          <input
            type="text"
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="请输入文章标题"
            className="form-input"
            required
          />
        </div>
        
        <div className="form-group">
          <label htmlFor="description">简介</label>
          <textarea
            id="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="请输入文章简介（选填）"
            className="form-textarea description-textarea"
            rows="3"
          />
        </div>
        
        <div className="form-group">
          <label htmlFor="content">正文 <span className="required">*</span></label>
          <textarea
            id="content"
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder="请输入文章正文"
            className="form-textarea content-textarea"
            rows="15"
            required
          />
        </div>
        
        <div className="form-actions">
          <button 
            type="button" 
            className="cancel-button" 
            onClick={goToHome}
          >
            取消
          </button>
          <button 
            type="submit" 
            className="submit-button" 
            disabled={isSubmitting}
          >
            {isSubmitting ? '发布中...' : '发布文章'}
          </button>
        </div>
      </form>
    </div>
  );
}

export default CreateArticlePage;
